package com.socool.facebook;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;

import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.model.GraphUser;

public class Act_Login_FB extends Activity {
	// Facebook facebook = new Facebook("559816754030978");

	Session.StatusCallback statusCallback = new SessionStatusCallback();
	private String LOG_TAG = "test";

	private boolean isOpen = false;

	String user_AccessToken;
	String user_Email;
	String user_ID;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(LOG_TAG, "[" + getLocalClassName() + "]" + "onCreate");

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.activity);

		Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

		Session session = Session.getActiveSession();
		if (session == null) {
			Log.d(LOG_TAG, "session is null");
			if (savedInstanceState != null) {
				Log.d(LOG_TAG, "restoreSession");
				session = Session.restoreSession(this, null, statusCallback,
						savedInstanceState);
			}
			if (session == null) {
				Log.d(LOG_TAG, "new Session(this)");
				session = new Session(this);
			}
			Log.d(LOG_TAG, "setActiveSession");
			Session.setActiveSession(session);
			Log.d(LOG_TAG, "session.getState(): " + session.getState());
			if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
				Log.d(LOG_TAG,
						"session.getState().equals(SessionState.CREATED_TOKEN_LOADED");
				session.openForRead(new Session.OpenRequest(this)
						.setCallback(statusCallback));
			} else {
				update();
			}

		} else {
			update();
		}

	}

	public void onResume() {
		Log.d(LOG_TAG, "[" + getLocalClassName() + "]" + "onResume");

		super.onResume();
	}

	public void onPause() {
		super.onPause();

	}

	private void update() {

		Session session = Session.getActiveSession();
		if (session.isOpened()) {
			Log.d(LOG_TAG, "[" + getLocalClassName() + "]isOpen: " + isOpen);
			if (isOpen == false) {
				Log.d(LOG_TAG, "[" + getLocalClassName() + "]"
						+ "update() session is Open");

				// get ID,Acess Token,E-mail
				getUserInfo(session);

				Bundle extra = new Bundle();
				Intent intent = new Intent(); // 초기화 깜빡 했다간
												// NullPointerException이라는 짜증나는
												// 놈이랑 대면하게 된다.

				// extra.putInt("data", 1);
				// intent.putExtras(extra);
				setResult(RESULT_OK, intent); // 성공했다는 결과값을 보내면서 데이터 꾸러미를 지고 있는
												// intent를 함께 전달한다.
				finish();
				/*
				 * 
				 * // 로그인모드를 저장한다. Manager_Shared mManagerShared = new
				 * Manager_Shared(this);
				 * mManagerShared.setPref_Loginstatus("facebook");
				 * 
				 * Intent i = new Intent(this, HomeActivity.class);
				 * startActivity(i);
				 * 
				 * overridePendingTransition(R.anim.fade,R.anim.hold); finish();
				 */

				isOpen = true;
			}

		} else {

			if (!session.isOpened() && !session.isClosed()) {
				session.openForRead(new Session.OpenRequest(this)
						.setCallback(statusCallback));
			} else {
				Log.d(LOG_TAG, "[" + getLocalClassName() + "]"
						+ "update() session is not Open openActiveSession");
				Session.openActiveSession(this, true, statusCallback);
			}
			/*
			 * if (!session.isOpened() && !session.isClosed()) {
			 * 
			 * Session.OpenRequest openRequest = null; openRequest = new
			 * Session.OpenRequest(this); if (openRequest != null) {
			 * 
			 * openRequest.setPermissions(Arrays.asList("email",
			 * "user_photos")); //
			 * openRequest.setPermissions(Arrays.asList("email"));
			 * 
			 * openRequest.setCallback(statusCallback);
			 * session.openForRead(openRequest); }
			 * 
			 * // session.openForRead(new //
			 * Session.OpenRequest(this).setCallback(statusCallback));
			 * 
			 * } else { Session.openActiveSession(this, true, statusCallback); }
			 */
		}

	}

	@Override
	public void onStart() {
		super.onStart();
		Session.getActiveSession().addCallback(statusCallback);
	}

	@Override
	public void onStop() {
		super.onStop();
		Session.getActiveSession().removeCallback(statusCallback);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d(LOG_TAG, "[" + getLocalClassName() + "]" + "onActivityResult()");
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		Session session = Session.getActiveSession();
		Session.saveSession(session, outState);
	}

	private class SessionStatusCallback implements Session.StatusCallback {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			Log.d(LOG_TAG, "[" + getLocalClassName() + "]"
					+ "SessionStatusCallback call()");
			update();

			/*
			 * Log.d(LOG_TAG, "Act_Login_FB   SessionStatusCallback call");
			 * Intent intent = new Intent(Act_Login_FB.this, FriendList.class);
			 * startActivity(intent);
			 * overridePendingTransition(R.anim.fade,R.anim.hold);
			 */
		}
	}

	private void getUserInfo(final Session session) {
		// Make an API call to get user data and define a
		// new callback to handle the response.
		Request request = Request.newMeRequest(session,
				new Request.GraphUserCallback() {
					@Override
					public synchronized void onCompleted(GraphUser user,
							Response response) {
						// If the response is successful

						Log.d(LOG_TAG, "onCompleted");
						if (session == Session.getActiveSession()) {
							if (user != null) {
								

								// Set the id for the ProfilePictureView
								// view that in turn displays the profile
								// picture.
								try {

									user_AccessToken = session.getAccessToken();

									Log.d(LOG_TAG, "session.getAccessToken(): "	+ user_AccessToken);
									Log.d(LOG_TAG,"session.getExpirationDate(): "+ session.getExpirationDate());

									user_ID = user.getId();
									Log.d(LOG_TAG, "user.getId: " + user_ID);
									JSONObject mJSONObject = user.getInnerJSONObject();

									user_Email = mJSONObject.getString("email");
									Log.d(LOG_TAG, "user.email: " + user_Email);
								} catch (Exception e) {

									Log.d(LOG_TAG, "ERROR: " + e.getMessage());
								}

								// sendServer();

							}
						}
						if (response.getError() != null) {
							// Handle errors, will do so later.

						}
					}

				});
		request.executeAsync();
	}

	/*
	 * private void sendServer() {
	 * 
	 * 
	 * try {
	 * 
	 * MySocketIO tos = new MySocketIO();
	 * 
	 * JSONObject json = new JSONObject(); json.put("id", user_ID);
	 * json.put("email", user_Email); json.put("accesstoken", user_AccessToken);
	 * 
	 * tos.emit(json);
	 * 
	 * 
	 * } catch (Exception e) { Log.d("test", "ERROR: "+e.getMessage()); }
	 * 
	 * 
	 * 
	 * }
	 */

}
